package hotel.quartz.oversea.job.switchs;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.MeituanConstants;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.SendUtils;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.job.base.BaseJob;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: lmf
 * @Date: 2021/04/21/9:51
 * @Description:
 */
@Slf4j
public class SwitchMakePushDataJob implements BaseJob {

    private String timestamp = "Smpdj"+String.valueOf(System.currentTimeMillis());

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;
    /**
     * 暂时 2秒一次   触发携程接口处理缓存变化数据
     * @param jobExecutionContext
     */
    @Override
    @SneakyThrows
    public void execute(JobExecutionContext jobExecutionContext) {
        log.info("todo Switchs Get Change Redis Data To Push Job {} >>>>>>>> 触发携程接口处理缓存变化数据定时器 执行时间: {}", timestamp, DateUtil.getCurrTime());
        Boolean zero = false;
        if((0==redisService.queueSize(MeituanConstants.REDIS_CHANGE_GOODS_DATA_MANY_HOTEL))){
            zero = true;
            //////////////电话预警  20210330 qyy//////////////////
            if(null == redisService.get("swmt_pop_change_goods_is_not_find_close")){
                if(null != redisService.get("swmt_pop_change_goods_is_not_find")){
                    String firstTime = (String)redisService.get("swmt_pop_change_goods_is_not_find");
                    String now = DateUtil.getCurrTime();
                    Long m = DateUtil.dateDiff(firstTime,"min",now,"yyyy-MM-dd HH:mm:ss");
                    if(m.intValue()>=2){
                        log.info("todo Switchs Get Change Redis Data To Push Job {} >>>>>>>> 上次变化价格房态为0，当前批次也为0，时间间隔：m={},firstTime={},now={}",m,firstTime,now);
                        if(null == redisService.get("swmt_pop_change_goods_is_not_find_has_send")){
                            log.info("todo Switchs Get Change Redis Data To Push Job {} >>>>>>>> 上次变化价格房态为0，当前批次也为0，将推送电话预警",m,firstTime,now);
                            SendUtils.sendWarnPhone("时间间隔"+m+"分钟，价格房态变化还是为零，请核实", 2,restTemplate);
                            redisService.setUnit("swmt_pop_change_goods_is_not_find_has_send",1,1L,TimeUnit.HOURS);
                        }
                    }
                }else{
                    redisService.setUnit("swmt_pop_change_goods_is_not_find", DateUtil.getCurrTime(),180L,TimeUnit.SECONDS);
                }
            }
        }else{
            //////////////电话预警  20210330 qyy//////////////////
            redisService.remove("swmt_pop_change_goods_is_not_find");
        }
        if(zero){
            log.info("todo Switchs Get Change Redis Data To Push Job {} >>>>>>>> 队列size=0，定时器不触发，该次定时器跳过: {},{},推送数据的长度为{}",timestamp, DateUtil.getCurrTime(),redisService.queueSize(MeituanConstants.REDIS_CHANGE_GOODS_DATA_MANY_HOTEL));
        }else{
            request();
        }
        log.info("todo Switchs Get Change Redis Data To Push Job {} >>>>>>>> 触发携程接口处理缓存变化数据定时器 结束时间: {},{}",timestamp, DateUtil.getCurrTime());

    }

    /**
     * 调用美团接口    主动查询上送的酒店是否存在变动数据，有则接口中操作存入缓存队列
     *
     * @return
     */
    private void request() {
        String callbackHost = CommonUrlConstants.CALLBACK_HOST;
        log.info("todo Switchs Get Change Redis Data To Push Job {} 触发携程接口处理缓存变化数据定时器 进入方法 request",timestamp);
        //发起请求
        Map params = new HashMap();
        Result response;
        long size2;
        long size = redisTemplate.opsForList().size(CommonConstants.SWITCH_CALLBACK_PUSH_DATA_QUEUE);
        int checkSize = 100;
        if(null != redisTemplate.opsForValue().get("todoSwitchsGetChangeRedisDataToPushJob_check_size_value")){
            checkSize = (Integer) redisTemplate.opsForValue().get("todoSwitchsGetChangeRedisDataToPushJob_check_size_value");
        }
        if(size>checkSize && null == redisTemplate.opsForValue().get("todoSwitchsGetChangeRedisDataToPushJob_check_size")){
            SendUtils.dingMsg("定时器处理产品价格房态队列异常！！请关注 ", DateUtil.getCurrTime()+" 队列待消费已超过"+checkSize+"，更新已堆积滞后 ", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            redisTemplate.opsForValue().set("todoSwitchsGetChangeRedisDataToPushJob_check_size",1,15,TimeUnit.MINUTES);
        }
        String checkGetChangeGoodsByOneHotelUrl = callbackHost+ UrlSwitchsEnums.goodsPrice.SWITCH_MAEE_PUSH_DATA.getValue();
        log.info("todo Switchs Get Change Redis Data To Push Job {} 触发携程接口处理缓存变化数据定时器  调用携程接口前，缓存队列size={}，该size不能作为依据，频繁变动因为 异步和主动同步在push",timestamp,size);
        response= JobRestTemplateUtils.post(checkGetChangeGoodsByOneHotelUrl, JSON.toJSONString(params),restTemplate);
        size2 = redisService.queueSize(CommonConstants.SWITCH_CALLBACK_PUSH_DATA_QUEUE);
        log.info("todo Switchs Get Change Redis Data To Push Job {} 触发携程接口处理缓存变化数据定时器  调用携程接口结束，缓存队列size={}，（该size不能作为依据，频繁变动因为 异步和主动同步在push）",timestamp,size2);
        if(response.getCode()== CommonConstants.SUCCESS){

        }else{
            //还原
            //redisTemplate.opsForList().leftPush(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS,String.valueOf(hotelId));
            log.error("todo Switchs Get Change Redis Data To Push Job {} 触发携程接口处理缓存变化数据定时器进入方法 request 返回失败：{},{}",timestamp, JSON.toJSONString(response), JSON.toJSONString(params));
        }

    }
}
